<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="卡次名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入卡次名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员信息" prop="meId">
        <el-input
          v-model="queryParams.meId"
          placeholder="请输入会员姓名|会员编号|联系电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="到期日期" prop="endTime">
       <el-date-picker
		 v-model="daterangeEndTime"
		 value-format="YYYY-MM-DD"
		 type="daterange"
		 range-separator="-"
		 start-placeholder="开始日期"
		 end-placeholder="结束日期"
	   ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in bus_count_sale_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['crm:countSale:add']"
        >办卡</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="countSaleList" style="height: calc(100vh - 330px);" @selection-change="handleSelectionChange">
      <el-table-column label="ID" width="180" align="center" prop="id">
		  <template #default="scope">
			  <el-link type="primary" @click="openRecord(scope.row)">{{scope.row.id}}</el-link>
		  </template>
	  </el-table-column>
      <el-table-column label="卡类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="bus_count_card_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="卡次名称" width="120" align="center" prop="name" />
      <el-table-column label="会员信息" width="180" align="left" prop="meId">
		  <template #default="scope">
			  {{scope.row.meNickname}} || <el-text style="margin-left: 5px;" type="info">{{scope.row.meId}}</el-text>
		  </template>
	  </el-table-column>
     <!-- <el-table-column label="开卡日期" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="到期日期" align="center" prop="endTime" width="180">
        <template #default="scope">
			<el-tooltip  effect="dark" :content="'开卡时间：'+parseTime(scope.row.startTime, '{y}-{m}-{d}')" placement="top">
				<el-text type="warning">{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</el-text>
			</el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="购买价格" align="center" prop="price" />
      <el-table-column label="购买次数" align="center" prop="numbers" />
      <el-table-column label="剩余次数" align="center" prop="specificNum">
		  <template #default="scope">
		  	<el-tooltip  effect="dark" :content="'最近消费时间：'+(scope.row.lastTime==null?'无': parseTime(scope.row.lastTime, '{y}-{m}-{d} {h}:{i}:{s}'))" placement="top">
		  		<el-text type="warning">{{scope.row.specificNum}}</el-text>
		  	</el-tooltip>
		  </template>
	  </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
		  <el-link v-if="scope.row.status=='0'" type="info">{{scope.row.text.status}}</el-link>
		<el-link  v-if="scope.row.status=='1'" type="warning">{{scope.row.text.status}}</el-link>
		  <el-link v-if="scope.row.status=='2'" @click="openCancelReason(scope.row.cancelReason)" type="danger">{{scope.row.text.status}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" width="120" show-overflow-tooltip prop="remark" />
      <el-table-column label="操作" fixed="right" width="180" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.status=='0'" icon="Postcard" @click="handleOpenCard(scope.row)" v-hasPermi="['crm:countSale:edit']">开卡</el-button>
		  <el-button link type="success" v-if="scope.row.status=='1'" icon="Money" @click="handleDownCard(scope.row)" v-hasPermi="['crm:countSale:edit']">下卡</el-button>
          <el-button link type="danger" v-if="scope.row.status!='2'" icon="Delete" @click="handleOffOpen(scope.row)" v-hasPermi="['crm:countSale:remove']">销卡</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改次卡销售对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" destroy-on-close append-to-body :close-on-click-modal="false">
      <el-form ref="countSaleRef" :model="form" :rules="rules" label-width="80px">
		  <el-row>
			  <el-col :span="24">
				  <el-form-item label="办卡会员" prop="meId">
					<meElSelectVue @change="meChange"></meElSelectVue>
				  </el-form-item>
			  </el-col>
		  </el-row>
		  <el-row>
			  <el-col :span="24">
				  <el-form-item label="次卡信息" prop="cardId">
					  <countElSelectVue @change="countChange"></countElSelectVue>
				  </el-form-item>
			  </el-col>
		  </el-row>
		  <el-row>
			  <el-col :span="12">
				  <el-form-item label="购买价格" prop="amount">
				    <el-input v-model="form.amount" disabled placeholder="请输入购买价格" />
				  </el-form-item>
			  </el-col>
			  <el-col :span="12">
				  <el-form-item label="购买次数" prop="numbers">
				    <el-input v-model="form.numbers" disabled placeholder="请输入购买次数" />
				  </el-form-item>
			  </el-col>
		  </el-row>
		  <el-row>
			  <el-col :span="16">
				  <el-form-item label="备注" prop="remark">
				    <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
				  </el-form-item>
			  </el-col>
		  </el-row>
		  <el-divider content-position="center">销售信息</el-divider>
		  <el-row>
			  <el-col :span="24">
				  <el-form-item label="销售人员" prop="belUserId">
				    <el-select v-model="form.belUserId" placeholder="请选择销售人员">
				  	<el-option v-for="user in listUsers" :key="user.userId" :label="user.nickName" :value="user.userName" />
				    </el-select>
				  </el-form-item>
			  </el-col>
		  </el-row>
		  <el-row>
			  <el-col :span="24">
				  <el-form-item label="收款方式" prop="payWay">
				    <el-radio-group v-model="form.payWay" >
				  	<el-radio v-for="dict in bus_pay_way" name="payWay" :label="dict.value">{{dict.label}}</el-radio>
				  	<el-radio v-if="form.meId!=null" name="payWay" label="99">储值卡<span style="color: red;font-size: 12px;">￥{{meInfo.storedAmount}}</span></el-radio>
				    </el-radio-group>
				  </el-form-item>
			  </el-col>
		  </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">下单办卡</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
	
	<el-dialog title="办理结果" :show-close="false" v-model="openResult" width="300px" destroy-on-close append-to-body :close-on-click-modal="false">
		<el-result
		        icon="success"
		        title="办卡成功"
		        sub-title="请及时开卡使用"
		      >
		        <template #extra>
		          <el-button type="primary" @click="openResult = false">关闭</el-button>
		        </template>
		      </el-result>
	</el-dialog>
	
	
	
	<el-dialog title="下卡" v-model="downOpen" width="400px" destroy-on-close append-to-body :close-on-click-modal="false">
	  <el-form ref="downCardRef" :model="downForm" :rules="downRules" label-width="80px">
		  <el-form-item label="卡次类型" prop="type">
			  <el-select v-model="downForm.type" disabled placeholder="请选择卡类型" clearable>
			    <el-option
			      v-for="dict in bus_count_card_type"
			      :key="dict.value"
			      :label="dict.label"
			      :value="dict.value"
			    />
			  </el-select>
		  </el-form-item>
		  <el-form-item label="次卡名称" prop="name">
			  <el-input v-model="downForm.name" disabled placeholder="请输入购买价格" />
		  </el-form-item>
		  <el-form-item label="会员信息" prop="meId">
			<el-input v-model="downForm.meId" disabled placeholder="请输入会员信息" />
		  </el-form-item>
		  <el-form-item label="购买次数" prop="numbers">
			<el-input v-model="downForm.numbers" disabled placeholder="请输入购买次数" />
		  </el-form-item>
		  <el-form-item label="剩余次数" prop="specificNum">
		  	<el-input v-model="downForm.specificNum" disabled placeholder="请输入购买次数" />
		  </el-form-item>
		  <el-form-item label="下卡次数" prop="count">
			   <el-input-number v-model="downForm.count" :min="1" :max="downForm.specificNum" />
		  </el-form-item>
		  <el-form-item label="备注" prop="remark">
		  	<el-input v-model="downForm.remark" type="textarea" placeholder="请输入备注" />
		  </el-form-item>
	  </el-form>
	  <template #footer>
	    <div class="dialog-footer">
	      <el-button type="primary" @click="doDownCard">下 卡</el-button>
	      <el-button @click="downOpen=false">取 消</el-button>
	    </div>
	  </template>
	</el-dialog>
	
	<el-dialog title="销卡" v-model="offOpen" width="400" :close-on-click-modal="false">
		 <el-form  ref="offCardRef" :model="offForm" label-width="auto" :rules="offRules">
		    <el-form-item label="卡类型" prop="type">
				  <el-select v-model="offForm.type" disabled placeholder="请选择卡类型" clearable>
					<el-option
					  v-for="dict in bus_count_card_type"
					  :key="dict.value"
					  :label="dict.label"
					  :value="dict.value"
					/>
				  </el-select>
		    </el-form-item>
		    <el-form-item label="次卡名称" prop="name">
				  <el-input v-model="offForm.name" disabled placeholder="请输入购买价格" />
		    </el-form-item>
		    <el-form-item label="会员信息" prop="meId">
				<el-input v-model="offForm.meId" disabled placeholder="请输入会员信息" />
		    </el-form-item>
		    <el-form-item label="购买次数" prop="numbers">
				<el-input v-model="offForm.numbers" disabled placeholder="请输入购买次数" />
		    </el-form-item>
			<el-alert type="warning" show-icon :closable="false">
			    <p>选中撤单回退将撤销该笔订单支付金额，已下卡不支持撤回订单支付金额！</p>
			</el-alert>
		    <el-form-item label="撤单回退" prop="rollback">
		    	<el-switch v-model="offForm.rollback" :disabled="offForm.status=='1'&&offForm.numbers!=offForm.specificNum" />
		    </el-form-item>
			<el-form-item label="销卡原因" prop="cancelReason">
				<el-input v-model="offForm.cancelReason" type="textarea" placeholder="请输入销卡原因" />
			</el-form-item>
		  </el-form>
		  <template #footer>
		    <div class="dialog-footer">
		      <el-button type="danger" @click="doOff">销 卡</el-button>
		      <el-button @click="offOpen=false">取 消</el-button>
		    </div>
		  </template>
	</el-dialog>
	
	<diffStoredAmount ref="diffStoredAmountRef" @success="successStored"/>
	
	<countRecordIndex ref="countRecordIndexRef"/>
  </div>
</template>

<script setup name="CountSale">
import { listCountSale,checkValid,openCard,downCard,offCard, getCountSale, delCountSale, addCountSale, updateCountSale } from "@/api/crm/countSale";
import { listUser } from "@/api/system/user";
import { localCardPay } from "@/api/crm/localOrder";

import meElSelectVue from "../memberInfo/meElSelect.vue";
import countElSelectVue from "../countCard/countElSelect.vue";

import diffStoredAmount from "../memberInfo/diffStoredAmount.vue";

import countRecordIndex from "../countRecord/index.vue"


const { proxy } = getCurrentInstance();
const { bus_count_card_type, bus_count_sale_status,bus_pay_way } = proxy.useDict('bus_pay_way','bus_count_card_type', 'bus_count_sale_status');

const countSaleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const daterangeEndTime = ref([]);

const openResult = ref(false);

const downOpen  = ref(false);

const offOpen = ref(false);

const diffStoredAmountRef = ref();

const countRecordIndexRef= ref();

const meInfo = ref({})

const listUsers = ref([])

const data = reactive({
  form: {payWay:'1'},
  downForm:{
  },
  offForm:{
	  
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cardId: null,
    type: null,
    name: null,
    meId: null,
    startTime: null,
    endTime: null,
    lastTime: null,
    price: null,
    numbers: null,
    specificNum: null,
    status: null,
    cancelReason: null,
  },
  rules: {
	  meId: [
	      { required: true, message: '请选择办卡会员', trigger: 'change' },
	  ],
	  cardId: [
	      { required: true, message: '请选择次卡信息', trigger: 'change' },
	  ],
	  belUserId: [
	      { required: true, message: '请选择销售人员', trigger: 'change' },
	  ],
	  payWay: [
	      { required: true, message: '请选择收款方式', trigger: 'change' },
	  ],
	  
  },
  downRules:{
	  count: [
	      { required: true, message: '请输入下卡次数', trigger: 'blur' },
	  ],
  },
  offRules:{
	  rollback: [
	      { required: true, message: '请勾选撤单回退', trigger: 'change' },
	  ],
	  cancelReason: [
	      { required: true, message: '请输入销卡原因', trigger: 'blur' },
	  ],
  }
});

const { queryParams, form, rules,downForm,downRules,offForm,offRules } = toRefs(data);

/** 查询次卡销售列表 */
function getList() {
  loading.value = true;
  
  queryParams.value.params = {};
  if (null != daterangeEndTime && '' != daterangeEndTime) {
      queryParams.value.params["beginEndTime"] = daterangeEndTime.value[0];
      queryParams.value.params["endEndTime"] = daterangeEndTime.value[1];
    }
  
  listCountSale(queryParams.value).then(response => {
    countSaleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
	meId: null,
    cardId: null,
    amount:null,
	numbers:null,
    currentAmount:null,
    discount:null,
    payWay:"1",
    belUserId:null,
	remark:null,
  };
  proxy.resetForm("countSaleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加次卡销售";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCountSale(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改次卡销售";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["countSaleRef"].validate(valid => {
    if (valid) {
		if('99'==form.value.payWay){
			//储值卡
			 if(meInfo.value.storedAmount<form.value.amount){
				 proxy.$modal.confirm('储值卡余额不足是否充值?').then(()=>{
					handleStored()
				 }).catch(()=>{})
				 return;
			 }
			 
		}
		
      //下单
	  checkValid(form.value.meId,form.value.cardId).then(response=>{
		  let _tip = response.data>0?'当前会员存在同类型有效次卡信息，是否继续开卡？':'确定下单开卡吗？';
		  proxy.$modal.confirm(_tip).then(function() {
		    return localCardPay(form.value);
		  }).then(() => {
			open.value = false;
			openResult.value = true;
			getList();
		  }).catch(() => {});
		  
	  })
	  
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除次卡销售编号为"' + _ids + '"的数据项？').then(function() {
    return delCountSale(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('crm/countSale/export', {
    ...queryParams.value
  }, `countSale_${new Date().getTime()}.xlsx`)
}


function meChange(params,info){
	//console.log('会员选择：',params,info)
	if(params){
		form.value.meId = params;
	}
	meInfo.value = info;
}


function countChange(params,info){
	if(params){
		form.value.cardId = params;
		
		
		form.value.amount = info.price;
		form.value.numbers = info.numbers
	}
}

function loadListUsers(){
	listUser().then(rsp=>{
		listUsers.value = rsp.rows;
	})
}


function handleStored(){
	diffStoredAmountRef.value.openWin(meInfo.value,'1')
}

//储值后回调
function successStored(value){
	meInfo.value.storedAmount = value
}


//点击开卡
function handleOpenCard(row){
	proxy.$modal.confirm('确定将编号为"' + row.id+ '"的次卡开卡吗？').then(function() {
	  return openCard(row.id)
	}).then(() => {
	  getList();
	  proxy.$modal.msgSuccess("开卡成功");
	}).catch(() => {});
}


//点击下卡
function handleDownCard(row){
	
	downForm.value = row;
	downForm.value.count = 1;
	downForm.value.remark = '';
	
	downOpen.value = true;
}

function doDownCard(){
	
	proxy.$refs["downCardRef"].validate(valid => {
	  if (valid) {
			let subData = {
				id:downForm.value.id,
				count:downForm.value.count,
				remark:downForm.value.remark
			}
			
			let diff = downForm.value.specificNum-subData.count;
			
			let _tip = '您确定下卡次数'+subData.count+'次吗,下卡后剩余'+diff+'次？';
			
			if(diff==0){
				_tip = '您确定下卡次数'+subData.count+'次，下卡后剩余次数将为0并销卡吗？';
			}
			
			proxy.$modal.confirm(_tip).then(function() {
			  return downCard(subData)
			}).then(() => {
			  getList();
			  proxy.$modal.msgSuccess("下卡成功");
			  downOpen.value = false
			}).catch(() => {});
	  }
	});
}

function handleOffOpen(row){
	offOpen.value = true;
	
	offForm.value = row;
	
	offForm.value.cancelReason=null;
	offForm.value.rollback = false;
}

function doOff(){
	proxy.$refs["offCardRef"].validate(valid => {
	  if (valid) {
		console.log(offForm.value)
		
		let subData = {
			id:offForm.value.id,
			rollback:offForm.value.rollback,
			cancelReason:offForm.value.cancelReason
		}
		
		let _tip = offForm.value.rollback?'您确定撤销该次卡，并撤销订单支付金额吗？':'您确定撤销该次卡吗？';
		
		proxy.$modal.confirm(_tip).then(function() {
		  return offCard(subData)
		}).then(() => {
		  getList();
		  proxy.$modal.msgSuccess("销卡成功");
		  offOpen.value = false
		}).catch(() => {});
		
		
	  }
	});
}


function openCancelReason(msg){
	 proxy.$modal.alert(msg,"销卡原因");
}

//打开使用记录
function openRecord(row){
	countRecordIndexRef.value.openWin(row.id);
}

getList();

loadListUsers();
</script>
